package com.minsu.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.minsu.entity.Listing;
import com.minsu.service.ListingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Controller
@RequestMapping("/listings")
public class ListingController {

    private static final Logger log = LoggerFactory.getLogger(ListingController.class);

    @Autowired
    private ListingService listingService;

    @GetMapping
    public String list(Model model,
                      @RequestParam(defaultValue = "1") long current,
                      @RequestParam(defaultValue = "10") long size,
                      @RequestParam(required = false) String title,
                      @RequestParam(required = false) BigDecimal minPrice,
                      @RequestParam(required = false) BigDecimal maxPrice,
                      @RequestParam(required = false) String district) {
        
        Page<Listing> page = listingService.search(
            new Page<>(current, size),
            title,
            minPrice,
            maxPrice,
            district
        );
        
        model.addAttribute("listings", page);
        model.addAttribute("districts", listingService.listDistricts());
        // 保存搜索条件，用于分页时保持搜索状态
        model.addAttribute("searchParams", new HashMap<String, Object>() {{
            put("title", title);
            put("minPrice", minPrice);
            put("maxPrice", maxPrice);
            put("district", district);
        }});
        
        return "listing/list";
    }

    @GetMapping("/data")
    @ResponseBody
    public Map<String, Object> listData(
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size,
            @RequestParam(required = false) String title,
            @RequestParam(required = false) BigDecimal minPrice,
            @RequestParam(required = false) BigDecimal maxPrice,
            @RequestParam(required = false) String district) {
        
        Page<Listing> page = listingService.search(
            new Page<>(current, size),
            title,
            minPrice,
            maxPrice,
            district
        );
        
        Map<String, Object> result = new HashMap<>();
        result.put("current", page.getCurrent());     // 当前页
        result.put("pages", page.getPages());         // 总页数
        result.put("total", page.getTotal());         // 总记录数
        result.put("size", page.getSize());           // 每页大小
        result.put("listings", page.getRecords());    // 数据列表
        
        // 添加日志
        log.info("Returning data: current={}, total={}, size={}, records={}", 
                page.getCurrent(), page.getTotal(), page.getSize(), page.getRecords().size());
        
        return result;
    }

    @GetMapping("/create")
    public String createForm(Model model) {
        model.addAttribute("listing", new Listing());
        model.addAttribute("districts", listingService.listDistricts());
        return "listing/form";
    }

    @GetMapping("/edit/{id}")
    public String editForm(@PathVariable String id, Model model) {
        Listing listing = listingService.getById(id);
        if (listing != null) {
            model.addAttribute("listing", listing);
        }
        model.addAttribute("districts", listingService.listDistricts());
        return "listing/form";
    }

    @PostMapping("/save")
    public String save(@ModelAttribute Listing listing) {
        listingService.saveOrUpdate(listing);
        return "redirect:/listings";
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable String id) {
        listingService.removeById(id);
        return "redirect:/listings";
    }

    @GetMapping("/districts")
    @ResponseBody
    public List<String> getDistricts() {
        return listingService.listDistricts();
    }

    @PostMapping("/import")
    @ResponseBody
    public Map<String, Object> importExcel(@RequestParam("file") MultipartFile file) {
        log.info("开始导入Excel文件：{}", file.getOriginalFilename());
        return listingService.importExcel(file);
    }
} 